package com.suvel.study.service.impl;

import com.suvel.study.dao.TokenDao;
import com.suvel.study.pojo.Token;
import com.suvel.study.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.Cookie;
import java.util.List;
import java.util.UUID;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenDao tokenDao;

    @Override
    public String createTokenCookie(String email) {
        String token = UUID.randomUUID().toString();
        Token saveToken = new Token(email, token);
        tokenDao.save(saveToken);
        return token;
    }

    @Override
    public String findEmailByToken(String token) {
        String email = null;
        List<Token> tokenList = tokenDao.findByToken(token);
        if(!CollectionUtils.isEmpty(tokenList)){
            Token tokenEntity = tokenList.get(0);
            email = tokenEntity.getEmail();
        }
        return email;
    }

    @Override
    public void deleteByEmail(String email) {
        tokenDao.deleteByEmail(email);
    }
}
